package com.anolesoft.amljmes.fourteenDispatch.service.impl;

import cn.hutool.core.util.StrUtil;
import com.anolesoft.amljmes.fourteenDispatch.dto.ChuangTouJiHuaEmpDTO;
import com.anolesoft.amljmes.fourteenDispatch.dto.EmpDTO;
import com.anolesoft.amljmes.fourteenDispatch.dto.MesPlanDispatchingDto;
import com.anolesoft.amljmes.fourteenDispatch.dto.MesProcessQlbzDO;
import com.anolesoft.amljmes.fourteenDispatch.service.mapper.MesPlanDispatchingServiceMapper;
import com.anolesoft.amljmes.fourteenDispatch.service.info.MesPlanDispatchingService;

import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.secondaryCostAccounting.util.NumStringUtil;
import com.anolesoft.yr.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

@Service
@Slf4j
public class MesPlanDispatchingServiceImpl implements MesPlanDispatchingService {
    @Autowired
    MesPlanDispatchingServiceMapper mesPlanDispatchingServiceMapper;


    @Override
    public List<MesPlanDispatchingDto> DispatchingSelectAll(String pacrNo) {
        return mesPlanDispatchingServiceMapper.DispatchingSelectAll(pacrNo);
    }

    @Override
    public int deleteDispatching(List<String> objuids) {
        int count = 0;
        for(String objuid : objuids) {
            count += mesPlanDispatchingServiceMapper.deleteDispatching(objuid);
        }
        return count;
    }

    @Override
    public int updateDispatching(List<String> objuids) {
        int count = 0;
        for(String objuid : objuids) {
            count += mesPlanDispatchingServiceMapper.updateDispatching(objuid,SecurityUtils.getLoginUser().getUserUid());
        }
        return count;
    }

    @Override
    public List<MesPlanDispatchingDto> orderSelectAll(String pacrNo) {
        return mesPlanDispatchingServiceMapper.orderSelectAll(pacrNo);
    }

    @Override
    public int addDispatching(List<MesPlanDispatchingDto> inFoDtoParam,String time,String czz) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        int count = 0;
        for (MesPlanDispatchingDto mesPlanDispatchingDto : inFoDtoParam) {
            mesPlanDispatchingDto.setPaigongren(loginUser.getEmpUid());
            mesPlanDispatchingDto.setFactoryId(loginUser.getFacCode());
            mesPlanDispatchingDto.setChecktimeStr(time);
            mesPlanDispatchingDto.setCaozuozhe(czz);
            if(czz == null || "".equals(czz.trim())){
                throw new RuntimeException("操作者为空");
            }
            count += mesPlanDispatchingServiceMapper.addDispatching(mesPlanDispatchingDto);
        }
        return count;
    }

    @Override
    public List<ChuangTouJiHuaEmpDTO> queryEmpEid() {
        List<ChuangTouJiHuaEmpDTO> gongxuNameAll=mesPlanDispatchingServiceMapper.queryEmpEid();
        return gongxuNameAll;
    }

    @Override
    public EmpDTO queryById(String objuid) {
        return mesPlanDispatchingServiceMapper.queryById(objuid);
    }

    @Override
    public int updateprocessstate(List<String> objuids) {
        int count = 0;
        for(String objuid : objuids) {
            count += mesPlanDispatchingServiceMapper.updateprocessstate(objuid);
        }
        return count;
    }

    /**
     * 新查询 增加计划开始时间 计划结束时间 紧急程度
     * 2022-11-22 新增可重复接单后同一个人已接单的信息不显示
     * @param pacrNo
     * @param factoryId
     * @param jiedanren
     * @return
     */
    @Override
    public List<MesPlanDispatchingDto> queryForJiedan(String pacrNo, String factoryId, String jiedanren) {
        List<MesPlanDispatchingDto> dispatchingDtos = this.mesPlanDispatchingServiceMapper.DispatchingSelectAll(pacrNo);
        List<MesPlanDispatchingDto> order = this.mesPlanDispatchingServiceMapper.orderSelectAll(pacrNo);
        List<MesPlanDispatchingDto> temp = new ArrayList<>();
        List<MesPlanDispatchingDto> result = new ArrayList<>();
        if (dispatchingDtos == null || dispatchingDtos.size() == 0) {
            temp = order;
        } else {
            int i = 1;
            for (MesPlanDispatchingDto mo:order) {
                boolean b = true;
                for (MesPlanDispatchingDto md:dispatchingDtos) {
                    if (mo.getGongxuid().equals(md.getGongxuid())){
                        if (md.getJiedanren().equals(jiedanren)) {
                            b = false;
                        } else {
                            mo.setObjuid(md.getObjuid());
                            mo.setJiedanren(jiedanren);
                        }
                        break;
                    }
                }
                if (b) {
                    mo.setNo(i);
                    i++;
                    temp.add(mo);
                }
            }
        }
        LocalDate endTime;
        if (this.mesPlanDispatchingServiceMapper.isfromtemp(pacrNo) == 0) {
            endTime = this.mesPlanDispatchingServiceMapper.checktimePlan(pacrNo);
        } else {
            endTime = this.mesPlanDispatchingServiceMapper.checktimeTemp(pacrNo);
        }
        if (endTime == null) {
            throw new RuntimeException("没有读取到考核日期，无法计算计划开工时间！");
        }
        LocalDate khrq = endTime;
        List<MesProcessQlbzDO> processQlbzDOS = this.mesPlanDispatchingServiceMapper.processQlbz(pacrNo,factoryId);
        NumStringUtil numStringUtil = new NumStringUtil();
        LocalDate startTime;
        //不满一天的剩余小时数
        String moretime = "0.00";
        //创建一个游标在迭代器末尾的迭代器
        ListIterator<MesPlanDispatchingDto> iterator = temp.listIterator(temp.size());
        //反向遍历
        while (iterator.hasPrevious()) {
            MesPlanDispatchingDto mesPlanDispatchingDto = iterator.previous();
            mesPlanDispatchingDto.setChecktime(khrq);
            // 计算期量时间 基础数据表里没有的按照8h计算
            String hour = "8.00";
            if (processQlbzDOS != null && processQlbzDOS.size() > 0) {
                for (MesProcessQlbzDO mesProcessQlbzDO:processQlbzDOS) {
                    if (mesPlanDispatchingDto.getGongxuname().equals(mesProcessQlbzDO.getGongxuname()) && mesPlanDispatchingDto.getGongxuid().equals(mesProcessQlbzDO.getGongxuid())) {
                        hour = mesProcessQlbzDO.getQiliangtime();
                        break;
                    }
                }
            }
            String qiliangDate = numStringUtil.numDiv(hour,"8");
            mesPlanDispatchingDto.setQiliang(qiliangDate);
            hour = numStringUtil.numAdd(hour,moretime);
            System.out.println("=======hour:" + hour);
            // 计算所需天数 一天按照8h计算
            System.out.println(numStringUtil.numDiv(hour,"8"));
            String[] time = numStringUtil.numDiv(hour,"8").split("\\.");
            System.out.println(time.length);
            //for (String t:time) {
            //    System.out.println(t);
            //}
            String days = time[0];
            //boolean previousDay = false;
            //if (numStringUtil.numCompareTo(time[1],"0").equals("0")) {
            //    startTime = endTime.minusDays(Integer.parseInt(days)-1);
            //    previousDay = true;
            //} else {
            startTime = endTime.minusDays(Integer.parseInt(days));
            //log.debug(startTime.toString());
            moretime = numStringUtil.numSub(hour,numStringUtil.numMul(days,"8"));
            //}
            mesPlanDispatchingDto.setPlanstarttime(startTime);
            mesPlanDispatchingDto.setPlanendtime(endTime);
            long jjcd=startTime.toEpochDay()-LocalDate.now().toEpochDay();
            int urgency= (int)jjcd;
            mesPlanDispatchingDto.setUrgency(urgency);
            // 每次插入开头
            result.add(0,mesPlanDispatchingDto);
            //if (previousDay) {
            //    endTime = endTime.minusDays(1);
            //} else {
            endTime = startTime;
            //}
        }
        log.debug("result:{}",result);
        return result;
    }

    /**
     * 接单方法
     * 接单人和操作者合一后二者数据相同
     * @param inFoDtoParam
     * @param czz
     * @param jiedanren
     * @param factory_id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int jiedan(List<MesPlanDispatchingDto> inFoDtoParam,String czz,String jiedanren,String factory_id) {
        if (czz == null || "".equals(czz.trim())) {
            throw new RuntimeException("操作者为空");
        }
        int count = 0;
        for (MesPlanDispatchingDto m : inFoDtoParam) {
            boolean update = false;
            if (!StrUtil.isEmptyOrUndefined(m.getJiedanren())){
                update = true;
            }
            m.setJiedanren(jiedanren);
            m.setFactoryId(factory_id);
            m.setCaozuozhe(czz);
            log.debug("jiedan"+count+":{}",m);
            if (update) {
                count += this.mesPlanDispatchingServiceMapper.updateJiedan(m);
            } else {
                count += this.mesPlanDispatchingServiceMapper.jiedan(m);
            }
        }
        return count;
    }

//    @Override
//    public ChuangTouJiHuaEmpDTO queryEmpEid(String objuid) {
//        return mesPlanDispatchingServiceMapper.queryEmpEid(objuid);
//    }
}


